package com.zysd.collection.scheduler.system.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.beanutils.PropertyUtilsBean;

import java.beans.PropertyDescriptor;
import java.util.HashMap;
import java.util.Map;

/**
 * bean工具类
 *
 * @author liuht
 */
public class BeanUtils {

    public static Map<String, Object> beanToMap(Object obj) {
        Map<String, Object> params = new HashMap<String, Object>(0);
        try {
            PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
            PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(obj);
            for (PropertyDescriptor descriptor : descriptors) {
                String name = descriptor.getName();
                if (!"class".equals(name)) {
                    params.put(name, propertyUtilsBean.getNestedProperty(obj, name));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return params;
    }

    /**
     * @param map   需要转换的map
     * @param clazz 目标javaBean的类对象
     * @return 目标类object
     */
    public static <T> T mapToBean(Map<String, Object> map, Class<T> clazz) {
        return JSONObject.toJavaObject(mapToJSONObject(map), clazz);
    }

    /**
     * Map转 JSONObject
     *
     * @param map map
     * @return JSONObject
     */
    public static JSONObject mapToJSONObject(Map<String, Object> map) {
        JSONObject jo = new JSONObject();
        jo.putAll(map);
        return jo;
    }
}
